package com.leftheart.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.leftheart.entity.Books;
import com.leftheart.entity.Rental;
import com.leftheart.service.BooksService;
import com.leftheart.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Controller
@RequestMapping("books")
public class BooksController {
    /**
     * Admin用户Controller
     */

    @Autowired
    BooksService booksService;

    @GetMapping("/list")
    public String queryAllBook(Model model) {
        List<Books> books = booksService.queryAllBook();
        model.addAttribute("books",books);
        return "admin/list";
    }

    @RequestMapping("/toindex")
    public String toIndex() {
        return "admin/index";
    }

    //重定向 list页面
    @RequestMapping("/comlist")
    public String comBack() {
        return "redirect:/books/list";
    }

    //跳转至添加书籍页面
    @GetMapping("/toadd")
    public String toadd(Rental rental,Model model) {
        model.addAttribute("rental",rental);
        return "admin/add";
    }


    @PostMapping("/add")
    public String addBook(Books books) {
        books.setBookDate();
        booksService.addBook(books);
        return "redirect:/books/list";
    }

    @RequestMapping("/drop/{bookId}")
    public String deleteBookById(@PathVariable("bookId") int bookId) {
        booksService.deleteBookById(bookId);
        return "redirect:/books/list";
    }

    @PostMapping("/query")
    public String queryBookByName(String bookName, Model model) {
        List<Books> books = booksService.queryBookByName(bookName);
        List<Books> list = new ArrayList<>();
        list.addAll(books);
        model.addAttribute("books", books);
        return "admin/list";
    }

    @GetMapping("/toupd/{bookId}")
    public String toupd(@PathVariable("bookId") int bookId, Model model) {
        Books books = booksService.queryBookById(bookId);
        model.addAttribute("bId", books);
        return "admin/update";
    }

    @PostMapping("/update")
    public String updateBook(Books books) {
        booksService.updateBook(books);
        return "redirect:/books/list";
    }

}